<script setup lang="ts">
import { ref, computed, useSlots, nextTick } from 'vue';
const props = defineProps<{
    modelValue: string;
    placeholder?: string;
    type?: string;
    maxLength?: number;
    minLength?: number;
    disabled?: boolean;
    clearable?: boolean;
    readonly?: boolean;
    showWordLimit?: boolean;
}>();
const slots = useSlots();
const emit = defineEmits<{
    (e: 'update:modelValue', value: string): void
}>();
// 输入框状态
const inputState = ref({
    focus: false,
    clear: false
});
// class列表
const classList = computed(() => {
    return {
        'nd-text-input-focus': inputState.value.focus,
        'nd-text-input-disabled': props.disabled,
    };
});
// 输入框聚焦
const onSetFocus = (type: boolean) => {
    inputState.value.focus = type;
    // 判断是否需要显示清除按钮
    nextTick(() => {
        if(props.clearable){
            inputState.value.clear = type;
        }
    });
};
// 清除输入框内容
const onClear = () => {
    emit('update:modelValue', '');
};
</script>
<template>
	<div
		class="nd-text-input"
		:class="classList"
	>
		<input
			class="nd-text-input-element"
			v-bind="$attrs"
			:value="modelValue"
			:placeholder="placeholder"
			:type="type"
			:disabled="disabled"
			:readonly="readonly"
			:maxlength="maxLength"
			:minlength="minLength"
			@input="emit('update:modelValue', ($event.target as HTMLInputElement).value)"
			@focus="onSetFocus(true)"
			@blur="onSetFocus(false)"
		>
		<template v-if="slots.suffix || inputState.clear">
			<div class="nd-text-input-suffix">
				<slot name="suffix">
					<span
						v-if="inputState.clear"
						class="nd-text-input-suffix-clear"
						@click="onClear"
					>x</span>
				</slot>   
			</div>
		</template>
	</div>
</template>